package com.siyoumi.app.modules.app_book.task;

import com.siyoumi.app.entity.BookOrder;
import com.siyoumi.app.modules.app_book.service.SvcBookOrder;
import com.siyoumi.component.XApp;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.config.SysConfig;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.task.EnumTask;
import com.siyoumi.task.TaskController;
import com.siyoumi.util.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

//检查所有服务器状态
//http://dev.x.siyoumi.com/task/app_book/task_order_share
@RestController
@RequestMapping("/task/app_book/task_order_share")
public class TaskOrderShare
        extends TaskController {

    @Override
    protected Boolean handle1() {
        return false;
    }

    @Override
    protected List handleData() {
        JoinWrapperPlus<BookOrder> query = SvcBookOrder.getApp().join();
        query.eq("border_status", 20)
                .eq("border_handle", 0)
                .lt("border_handle_date", XDate.now());
        if (!SysConfig.getBean().isDev()) {
            query.le("border_date_end_final", XDate.today().minusDays(1)); //退房+1天后入帐
        }
        query.orderByAsc("border_date_end_final");

        return SvcBookOrder.getApp().get(query);
    }

    @Override
    protected void handleBefore(Object data) {
        BookOrder entity = (BookOrder) data;

        BookOrder entityOrderUpdate = new BookOrder();
        entityOrderUpdate.setBorder_id(entity.getKey());
        entityOrderUpdate.setBorder_handle_date(XDate.now().plusMinutes(3));
        SvcBookOrder.getApp().updateById(entityOrderUpdate);
    }

    @Override
    protected XReturn handle(Object data) {
        BookOrder entity = (BookOrder) data;
        XHttpContext.setX(entity.getBorder_x_id());

        XApp.getTransaction().execute(status -> {
            XReturn r = SvcBookOrder.getBean().sharePrice(entity);

            //更新分帐状态
            BookOrder entityOrderUpdate = new BookOrder();
            entityOrderUpdate.setBorder_id(entity.getKey());
            entityOrderUpdate.setBorder_handle(10);
            if (r.ok()) {
                entityOrderUpdate.setBorder_handle(1);
            }
            entityOrderUpdate.setBorder_handle_date(XDate.now());
            SvcBookOrder.getApp().updateById(entityOrderUpdate);

            return r;
        });


        return EnumTask.RUN.getR();
    }
}
